package com.tomcat;

import com.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class TomCat {

    // key:url-pattern value:servlet-name
    private static ConcurrentHashMap<String, String> concurrentMappingHashMap = new ConcurrentHashMap<>();
    // key:servlet-name value:servlet-class的实例
    private static ConcurrentHashMap<String, HttpServlet> concurrentServletHashMap = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        TomCat tomCat = new TomCat();
        tomCat.init();
        tomCat.run();
    }

    public void init() {
        String path = TomCat.class.getResource("/").getPath();
        System.out.println(path);

        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(new File(path + "web.xml"));
            Element rootElement = document.getRootElement();
            // 获取servlet列表
            List<Element> servletList = rootElement.elements("servlet");
            for (Element servlet : servletList) {
                String key = servlet.element("servlet-name").getText();
                String value = servlet.element("servlet-class").getText();
                concurrentServletHashMap.put(key, (HttpServlet) Class.forName(value).newInstance());
//                System.out.println("servlet-name: " + key);
//                System.out.println("servlet-class: " + value);
            }
            // 获取servlet-mapping列表
            List<Element> servletMappingList = rootElement.elements("servlet-mapping");
            for (Element servletMapping : servletMappingList) {
                String key = servletMapping.element("url-pattern").getText();
                String value = servletMapping.element("servlet-name").getText();
                concurrentMappingHashMap.put(key, value);
//                System.out.println("url-pattern: " + key);
//                System.out.println("servlet-name: " + value);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            while (!serverSocket.isClosed()) {
                Socket socket = serverSocket.accept();
                // 创建并启动一个线程来处理当前Http请求
                new Thread(new TomCatThread(socket)).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static ConcurrentHashMap<String, String> getConcurrentMappingHashMap() {
        return concurrentMappingHashMap;
    }

    public static ConcurrentHashMap<String, HttpServlet> getConcurrentServletHashMap() {
        return concurrentServletHashMap;
    }
}
